<template>
  <div class="conversation-container">
    <!-- 对话历史区域 -->
    <div class="chat-history" ref="chatHistory">
      <div
        v-for="(message, index) in messages"
        :key="index"
        :class="['message', message.type]"
      >
        <div class="avatar">
          <img
            :src="message.type === 'system' ? systemAvatar : userAvatar"
            :alt="message.type === 'system' ? '系统头像' : '用户头像'"
          />
        </div>
        <div class="message-content">
          <div
            class="message-text"
            v-if="message.fullyDisplayed || message.type === 'user'"
          >
            {{ message.content }}
          </div>
          <div class="message-text typing" v-else>
            {{ message.displayText }}
            <span class="cursor">|</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 当前选项区域 -->
    <div
      class="options-container"
      v-if="
        currentOptions.length > 0 &&
        !loading &&
        canShowOptions &&
        !conversationEnded
      "
    >
      <div class="options-title">请选择：</div>
      <div class="options-list">
        <button
          v-for="option in currentOptions"
          :key="option.id"
          class="option-button"
          @click="selectOption(option)"
        >
          {{ option.scene }}
        </button>
      </div>
    </div>

    <!-- 对话结束提示 -->
    <div class="conversation-end" v-if="conversationEnded">
      <div class="end-message">
        <div class="avatar">
          <img :src="systemAvatar" alt="系统头像" />
        </div>
        <div class="message-content">本次对话已结束，感谢您的参与！</div>
      </div>
      <button class="restart-button" @click="restartConversation">
        重新开始对话
      </button>
    </div>

    <!-- 加载状态 -->
    <div class="thinking" v-if="loading">
      <div class="avatar">
        <img :src="systemAvatar" alt="系统头像" />
      </div>
      <div class="message-content">
        <div class="thinking-dots">
          <span></span>
          <span></span>
          <span></span>
        </div>
      </div>
    </div>

    <!-- 错误提示 -->
    <div class="error-message" v-if="error">
      {{ error }}
      <button class="retry-button" @click="retryLastAction">重试</button>
    </div>

    <!-- 底部标签栏 -->
    <div class="tab-bar">
      <div class="tab-item" @click="setActiveTab('home')">
        <i class="fas fa-home tab-icon"></i>
        <span>首页</span>
      </div>
      <div class="tab-item" @click="setActiveTab('referral')">
        <i class="fas fa-hand-holding-heart tab-icon"></i>
        <span>一键转介</span>
      </div>
      <div class="tab-item" @click="setActiveTab('resources')">
        <i class="fas fa-seedling tab-icon"></i>
        <span>我的资源</span>
      </div>
    </div>
  </div>
</template>

<script>
import { getRiskConversation } from "../../api/manager";

export default {
  data() {
    return {
      messages: [], // 对话历史
      currentOptions: [], // 当前选项
      loading: false, // 加载状态
      error: "", // 错误信息
      conversationEnded: false, // 对话是否结束
      canShowOptions: true, // 是否可以显示选项
      systemAvatar:
        "https://lesson.iapeap.com/DRM/IMG/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20251120162701_1860_138.png", // 系统头像SVG
      userAvatar:
        "", // 用户头像SVG
    };
  },
  created() {
    // 初始化对话
    this.initConversation();

    // 获取缓存的性别
    if (localStorage.getItem("userinfo")) {
      let userinfo = JSON.parse(localStorage.getItem("userinfo"));
      if (userinfo.gender === "M") {
        console.log("用户性别为男");
        this.userAvatar = "https://lesson.iapeap.com/DRM/IMG/nan.png";
      } else {
        this.userAvatar = "https://lesson.iapeap.com/DRM/IMG/nv.png";
      }
    }
  },
  methods: {
    setActiveTab(tab) {
      this.activeTab = tab;
      // 在实际应用中，这里会加载对应标签的内容
      if (tab === "home") {
        this.$router.push("/managerHome");
      } else if (tab === "referral") {
        this.$router.push("/yijianzhuanjie");
      } else if (tab === "resources") {
        this.$router.push("/weijiganyu");
      }
    },
    // 初始化对话
    initConversation() {
      this.loading = true;
      this.error = "";
      this.conversationEnded = false;
      this.canShowOptions = true;

      let data = {
        id: "0",
      };

      getRiskConversation(data)
        .then((res) => {
          this.loading = false;
          if (res.code === 200) {
            this.currentOptions = res.data;
            // 添加系统初始消息
            this.addSystemMessage(
              "您当前可能面临很大压力，希望能在这个时候给到你支持。您遇到的事件主要属于哪一类别？"
            );
          } else {
            this.error = res.message || "获取数据失败";
          }
        })
        .catch((err) => {
          this.loading = false;
          this.error = "网络错误，请稍后重试";
          console.error("获取对话数据失败:", err);
        });
    },

    // 选择选项
    selectOption(option) {
      // 添加用户选择到对话历史
      this.addUserMessage(option.scene);

      this.loading = true;
      this.error = "";
      this.canShowOptions = false; // 点击后立即隐藏选项，防止重复点击

      let data = {
        id: option.id.toString(),
      };

      getRiskConversation(data)
        .then((res) => {
          this.loading = false;
          if (res.code === 200) {
            this.handleResponseData(res.data);
          } else {
            this.error = res.message || "获取数据失败";
            this.canShowOptions = true; // 出错时恢复选项显示
          }
        })
        .catch((err) => {
          this.loading = false;
          this.error = "网络错误，请稍后重试";
          this.canShowOptions = true; // 出错时恢复选项显示
          console.error("获取对话数据失败:", err);
        });
    },

    // 处理接口返回的数据
    handleResponseData(data) {
      // 检查返回的数据是否为空
      if (!data || data.length === 0) {
        // 数据为空，表示对话结束
        this.currentOptions = [];
        this.conversationEnded = true;
        this.addSystemMessage(
          "感谢您的参与，我们已经收集到您的选择信息。",
          () => {
            this.scrollToBottom();
          }
        );
        return;
      }

      // 根据type字段处理不同类型的数据
      const firstItem = data[0];

      switch (firstItem.type) {
        case 1: // 问题类型
          this.handleQuestionType(data);
          break;
        case 2: // 答案/选项类型
          this.handleAnswerType(data);
          break;
        case 3: // 结束语类型
          this.handleEndType(data);
          break;
        default:
          console.warn("未知的type类型:", firstItem.type);
          this.handleAnswerType(data); // 默认按选项处理
      }
    },

    // 处理问题类型 (type=1)
    handleQuestionType(data) {
      // 显示问题内容
      this.addSystemMessage(data[0].scene, () => {
        // 打字效果完成后，如果有后续选项，则自动请求下一级
        if (data[0].id) {
          this.loading = true;
          let nextData = {
            id: data[0].id.toString(),
          };

          getRiskConversation(nextData)
            .then((res) => {
              this.loading = false;
              if (res.code === 200) {
                this.handleResponseData(res.data);
              } else {
                this.error = res.message || "获取数据失败";
                this.canShowOptions = true;
              }
            })
            .catch((err) => {
              this.loading = false;
              this.error = "网络错误，请稍后重试";
              this.canShowOptions = true;
              console.error("获取对话数据失败:", err);
            });
        } else {
          // 如果没有id，直接显示选项（如果有的话）
          if (data.length > 1) {
            this.currentOptions = data.slice(1);
            this.canShowOptions = true;
          }
        }
      });
    },

    // 处理答案/选项类型 (type=2)
    handleAnswerType(data) {
      // 检查是否需要添加引导语（根据parent_id判断层级）
      const needsGuidance = this.shouldAddGuidance(data[0].parent_id);

      if (needsGuidance) {
        this.addSystemMessage(
          "感谢您告诉我，这能帮我为您提供更精准的支持。请进一步描述，这个事件更符合以下哪种具体场景？",
          () => {
            this.currentOptions = data;
            this.canShowOptions = true;
          }
        );
      } else {
        // 直接显示选项
        this.currentOptions = data;
        this.canShowOptions = true;
      }
    },

    // 处理结束语类型 (type=3)
    handleEndType(data) {
      // 显示结束内容
      this.addSystemMessage(data[0].scene, () => {
        // 打字效果完成后结束对话
        this.currentOptions = [];
        this.conversationEnded = true;

        // 添加结束提示
        setTimeout(() => {
          this.addSystemMessage("以上是相关建议，希望对您有所帮助。", () => {
            this.scrollToBottom();
          });
        }, 500);
      });
    },

    // 判断是否需要添加引导语
    shouldAddGuidance(parentId) {
      // 根据你的业务逻辑，判断在什么情况下需要添加引导语
      // 这里根据parent_id的范围判断，你可以根据实际需求调整
      return parentId >= 7 && parentId <= 10;
    },

    // 添加系统消息（带打字效果）
    addSystemMessage(content, onComplete = null) {
      const message = {
        type: "system",
        content: content,
        displayText: "",
        fullyDisplayed: false,
      };

      this.messages.push(message);

      // 滚动到底部
      this.$nextTick(() => {
        this.scrollToBottom();

        // 根据内容长度调整打字速度
        const speed = content.length > 200 ? 10 : 30;

        // 打字效果
        this.typeMessage(message, 0, speed, onComplete);
      });
    },

    // 打字效果实现
    typeMessage(message, index, speed, onComplete = null) {
      if (index < message.content.length) {
        message.displayText += message.content.charAt(index);
        setTimeout(() => {
          this.typeMessage(message, index + 1, speed, onComplete);
          // 打字过程中持续滚动到底部
          this.scrollToBottom();
        }, speed);
      } else {
        message.fullyDisplayed = true;
        // 打字完成后执行回调
        if (onComplete) {
          onComplete();
        }
      }
    },

    // 添加用户消息（立即显示）
    addUserMessage(content) {
      this.messages.push({
        type: "user",
        content: content,
        fullyDisplayed: true,
      });

      // 滚动到底部
      this.$nextTick(() => {
        this.scrollToBottom();
      });
    },

    // 滚动到对话底部
    scrollToBottom() {
      const container = this.$refs.chatHistory;
      if (container) {
        // 使用平滑滚动效果
        container.scrollTo({
          top: container.scrollHeight,
          behavior: "smooth",
        });
      }
    },

    // 重新开始对话
    restartConversation() {
      this.messages = [];
      this.currentOptions = [];
      this.conversationEnded = false;
      this.canShowOptions = true;
      this.initConversation();
    },

    // 重试上次操作
    retryLastAction() {
      this.error = "";
      if (this.conversationEnded) {
        this.restartConversation();
      } else if (this.currentOptions.length === 0) {
        this.initConversation();
      }
    },
  },
  watch: {
    // 监听对话结束状态，当对话结束时滚动到底部
    conversationEnded(newVal) {
      if (newVal) {
        this.$nextTick(() => {
          this.scrollToBottom();
        });
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.conversation-container {
  max-width: 600px;
  margin: 0 auto;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  min-height: 100vh;
  font-family: "PingFang SC", "Helvetica Neue", Arial, sans-serif;
  display: flex;
  flex-direction: column;
  padding: 20px 5px;
  box-sizing: border-box;
  padding-bottom: 100px;
}

.chat-history {
  flex: 1;
  overflow-y: auto;
  padding: 10px;
  margin-bottom: 20px;
  display: flex;
  flex-direction: column;
  // 添加滚动条样式
  &::-webkit-scrollbar {
    width: 6px;
  }

  &::-webkit-scrollbar-track {
    background: rgba(0, 0, 0, 0.05);
    border-radius: 3px;
  }

  &::-webkit-scrollbar-thumb {
    background: rgba(0, 0, 0, 0.2);
    border-radius: 3px;
  }
}

.message {
  display: flex;
  margin-bottom: 25px; // 减少间距，但仍然保持清晰的分隔
  animation: fadeInUp 0.5s ease;
  align-items: flex-start; // 确保头像和消息顶部对齐

  &.user {
    flex-direction: row-reverse;

    .avatar {
      margin-left: 12px; // 用户头像与消息间距
      margin-right: 0;
    }

    .message-content {
      background-color: #1890ff;
      color: white;
      border-radius: 18px 4px 18px 18px;
      margin-left: 0;
      margin-right: 0;
    }
  }

  &.system {
    .avatar {
      margin-right: 12px; // 系统头像与消息间距
      margin-left: 0;
    }

    .message-content {
      background: white;
      color: #333;
      border-radius: 4px 18px 18px 18px;
      box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
      margin-right: 0;
      white-space: pre-line; // 保留换行符
      position: relative;
      top: 15px;
    }
  }

  .avatar {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    overflow: hidden;
    flex-shrink: 0;
    margin-top: 5px; // 头像稍微下移，与消息顶部对齐

    img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
  }

  .message-content {
    max-width: 75%; // 稍微增加最大宽度
    padding: 12px 16px;
    line-height: 1.5;
    word-break: break-word;
    position: relative;
    top: 15px;
  }
}

// 打字效果
.typing {
  .cursor {
    animation: blink 1s infinite;
    color: #1890ff;
  }
}

@keyframes blink {
  0%,
  100% {
    opacity: 1;
  }
  50% {
    opacity: 0;
  }
}

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.options-container {
  background: rgba(255, 255, 255, 0.9);
  border-radius: 16px;
  padding: 16px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
  animation: slideUp 0.5s ease;
}

@keyframes slideUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.options-title {
  font-size: 16px;
  color: #666;
  margin-bottom: 12px;
  font-weight: 500;
}

.options-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.option-button {
  background: rgba(255, 255, 255, 0.8);
  border: 1px solid rgba(24, 144, 255, 0.3);
  border-radius: 12px;
  padding: 14px 18px;
  text-align: left;
  font-size: 15px;
  color: #1890ff;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);

  &:hover {
    background: rgba(24, 144, 255, 0.1);
    border-color: #1890ff;
    transform: translateY(-2px);
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  }

  &:active {
    transform: translateY(0);
    box-shadow: 0 2px 3px rgba(0, 0, 0, 0.1);
  }
}

.conversation-end {
  text-align: center;
  padding: 20px;
  animation: fadeIn 0.5s ease;

  .end-message {
    display: flex;
    justify-content: center;
    margin-bottom: 20px;

    .avatar {
      width: 40px;
      height: 40px;
      border-radius: 50%;
      overflow: hidden;
      margin-right: 10px;

      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
    }

    .message-content {
      background: white;
      padding: 12px 18px;
      border-radius: 18px;
      max-width: 70%;
      box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
    }
  }
}

.restart-button {
  background: linear-gradient(135deg, #ff6b6b 0%, #ee5a24 100%);
  color: white;
  border: none;
  border-radius: 25px;
  padding: 12px 30px;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 4px 10px rgba(255, 107, 107, 0.3);

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 15px rgba(255, 107, 107, 0.4);
  }
}

.thinking {
  display: flex;
  margin-bottom: 20px;
  align-items: center;

  .avatar {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    overflow: hidden;
    margin-right: 10px;

    img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
  }

  .message-content {
    background: white;
    border-radius: 18px;
    padding: 12px 18px;
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
  }
}

.thinking-dots {
  display: flex;
  align-items: center;
  height: 20px;

  span {
    display: inline-block;
    width: 8px;
    height: 8px;
    border-radius: 50%;
    background: #999;
    margin: 0 3px;
    animation: thinking 1.4s infinite ease-in-out both;

    &:nth-child(1) {
      animation-delay: -0.32s;
    }

    &:nth-child(2) {
      animation-delay: -0.16s;
    }
  }
}

@keyframes thinking {
  0%,
  80%,
  100% {
    transform: scale(0.8);
    opacity: 0.5;
  }
  40% {
    transform: scale(1);
    opacity: 1;
  }
}

.error-message {
  background: rgba(255, 77, 79, 0.1);
  border: 1px solid #ff4d4f;
  border-radius: 8px;
  padding: 12px 16px;
  color: #a8071a;
  text-align: center;
  margin-top: 10px;
}

.retry-button {
  background: #ff4d4f;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 6px 12px;
  margin-left: 10px;
  cursor: pointer;
  font-size: 14px;

  &:hover {
    background: #d9363e;
  }
}

// 响应式设计
@media (max-width: 480px) {
  .message .message-content {
    max-width: 80%;
  }

  .message .avatar {
    width: 36px;
    height: 36px;
  }
}

/* 底部标签栏 */
.tab-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 70px;
  background-color: rgba(255, 255, 255, 0.95);
  display: flex;
  border-top: 1px solid #e8e8e8;
  z-index: 10;
  padding: 0 10px;
}

.tab-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  font-size: 11px;
  color: #8e8e93;
  cursor: pointer;
  transition: all 0.2s ease;
  border-radius: 8px;
  margin: 5px;
}

.tab-item.active {
  color: #8e7cc3;
  background-color: rgba(142, 124, 195, 0.08);
}

.tab-icon {
  font-size: 20px;
  margin-bottom: 4px;
  transition: all 0.2s ease;
}

.tab-item.active .tab-icon {
  transform: translateY(-2px);
}
.btn-container {
  position: absolute;
  bottom: 12%;
}
.btn-container .btnpupor {
  background-color: #a293b8;
  margin: 1rem;
  padding: 5px 30px;
  color: #fff;
  border-radius: 20px;
}
</style>
